<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Home</title>

    <script src="../public/vue/dist/vue.min.js"></script>
    <!-- Bootstrap CSS -->
    <link href="../public/bootstrap/dist/css/bootstrap.css" rel="stylesheet">
    <!-- jQuery -->
    <script src="../public/jquery/dist/jquery.min.js"></script>
    <!-- Bootstrap JavaScript -->
    <script src="../public/bootstrap/dist/js/bootstrap.min.js"></script>




    <link rel="stylesheet" href="../public/summernote/dist/summernote.css">

    <script src="../public/summernote/dist/summernote.js"></script>
    <script src="../public/summernote/dist/lang/summernote-zh-CN.js"></script>

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.3/html5shiv.js"></script>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body>



    <div class="container" id="noteItemApp" style="margin: 50px auto;">

        <div class="panel panel-info">

            <div class="panel-body">
                <form class="navbar-form navbar-right">
                    <div class="form-group">
                        <label for="firstname" class="control-label">分类</label>
                        <div class="input-group">

                            <select v-model="noteItemSearchForm.cateId" class="form-control">
                                <option value=""> ==</option>
                                <option v-for="option in noteCateList" v-bind:value="option._id">
                                    {{ option.sname }}
                                </option>
                            </select>
                        </div>


                    </div>
                    <div class="form-group">
                        <label for="firstname" class="control-label">名称</label>
                        <div class="input-group">
                            <input type="text" v-model="noteItemSearchForm.sname" class="form-control">
                        </div>
                    </div>
                    <button type="button" @click="queryItem" class="btn btn-primary">搜索</button>
                </form>
            </div>
        </div>



        <button type="button" @click="fnClear" class="btn btn-success">add</button>
        <div class=" pull-right">
            <!-- <strong>共{{total}}条</strong>
            <p>{{pages}}</p> -->
            <ul class="pagination">
                
                <button type="button" @click="fnLastPage" class="btn btn-link"><i class="glyphicon glyphicon-chevron-left" ></i></button>


                <input type="number" style="width: 50px;" v-model="page" @change="queryItem" min="1" :max="pages"> 
                 / {{pages}}

                <!-- <li v-for="n in pages">
                    <button type="button" @click="fnPageChange(n)" class="btn btn-link">{{n}}</button>
                </li> -->
                <button type="button" @click="fnNextPage" class="btn btn-link"><i class="glyphicon glyphicon-chevron-right" ></i></button>
            </ul>

        </div>

        <table class="table table-condensed table-bordered">
            <thead>
                <tr>
                    <th>名称</th>
                    <th>创建时间</th>
                    <th>是否完成</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item, index) in noteItemList" :key="index">
                    <td>

                        <button type="button" @click="fnUpdateItemModal(item)" class="btn btn-link">{{item.sname}}</button>

                    </td>
                    <td>{{item.ctime}}</td>
                    <td>
                        <span class="label label-success" v-if="item.doneFlag">完成</span>
                        <span class="label label-default" v-if="!item.doneFlag">未完成</span>



                    </td>
                    <td>

                        <!-- <button type="button" @click="fnUpdateItemModal(item)" class="btn btn-primary">modify</button> -->
                        <button type="button" class="btn btn-danger">delete</button>

                    </td>
                </tr>
            </tbody>
        </table>


        <!-- add form  -->

        <div class="alert alert-success">
            <form role="form">
                <div class="form-group" v-show="true">
                    <label for="firstname">分类</label>
                    <div>

                        <div class="checkbox">
                            <label v-for="item in noteCateList" :key="item.id" class="radio-inline">
                                <input type="radio" name="cate" :value="item._id" v-model="noteItemForm.cateId">{{item.sname}}
                            </label>

                        </div>
                    </div>
                </div>
                <div class="form-group" v-show="false">
                    <label for="firstname">_id</label>
                    <input type="text" name="" id="input" class="form-control" v-model="noteItemForm._id">
                </div>
                <div class="form-group">
                    <label for="firstname">名字</label>
                    <input type="text" name="" id="input" class="form-control" v-model="noteItemForm.sname">
                </div>
                <div class="form-group">
                    <label for="firstname">说明</label>

                    <textarea v-model="noteItemForm.snote" class="form-control" rows="5" required="required"></textarea>

                </div>
                <div class="form-group">
                    <!-- <label for="firstname" >是否完成</label> -->
                    <div class="checkbox">
                        <label>
                            <input type="checkbox" v-model="noteItemForm.doneFlag">已完成
                        </label>
                    </div>
                </div>



                <div class="form-group">
                    <!-- <div class="col-sm-offset-2 col-sm-10"> -->
                    <button type="button" @click="fnAddOrUpdate" class="btn btn-primary">保存</button>
                    <!-- </div> -->
                </div>
            </form>

            <button type="button" @click="fnArticleModal" class="btn btn-success">add article</button>


            <div v-for="item in noteArticleList" :key="item.id">
                <p class="navbar-text">
                    <button type="button" @click="fnShowDetail(item)" class="btn btn-link">{{item.sname}}</button>
                </p>
            </div>
        </div>


        <!-- add  article  -->

        <!-- 模态框（Modal） -->
        <div class="modal fade  bs-example-modal-lg" id="addArticleModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
            aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                        <h4 class="modal-title" id="myModalLabel">提示</h4>
                    </div>
                    <div class="modal-body">


                        <form class="navbar-form pull-right">
                            <button type="button" @click="fnAddArticle" class="btn btn-link">保存</button>
                        </form>


                        <div class="clearfix">

                        </div>
                        <form role="form">
                            <div class="form-group" v-show="false">
                                <label>itemId</label>
                                <input type="text" v-model="noteArticleForm.itemId" class="form-control">

                            </div>
                            <div class="form-group" v-show="false">
                                <label>_id</label>
                                <input type="text" name="" id="input" class="form-control" v-model="noteArticleForm._id">
                            </div>
                            <div class="form-group">
                                <label>名字</label>
                                <input type="text" name="" id="input" class="form-control" v-model="noteArticleForm.sname">
                            </div>
                            <div class="form-group">
                                <label>正文</label>
                                <textarea id="summernote1" v-model="noteArticleForm.stext" class="form-control" rows="10"></textarea>

                            </div>

                        </form>

                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button type="button" @click="fnAddArticle" class="btn btn-primary">确定</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div>
        <!-- /.modal -->




    </div>



    </div>


</body>

</html>

<script>
    var vm = new Vue({
        el: '#noteItemApp',
        data: {

            total: 0,
            page: 1,
            noteItemSearchForm: {
                cateId: '',
                sname: '',
            },

            //form
            noteItemForm: {
                cateId: '',
            },

            noteCateList: [],

            noteItemList: [],

            noteArticleForm: {
                itemId: '',
            },

            // noteArticleDetail: {},
            noteArticleList: [],



        },

        computed: {

            pages() {
                return Math.ceil(this.total / 10);
            }
        },
        methods: {

            //新增 item的 rule
            itemRule() {

                return [
                    {
                        name: this.noteItemForm.cateId,
                        validators: {
                            notEmpty: {
                                tip: "分类不能为空"
                            },
                        }
                    },
                    {
                        name: this.noteItemForm.sname,
                        validators: {
                            notEmpty: {
                                tip: "名字不能为空"
                            },
                            // regexp: {
                            //     reg: /^[a-zA-Z0-9_]+$/,
                            //     tip: '名字只能包含大写、小写、数字和下划线'
                            // }
                        }
                    }];
            },
            //新增 article 的 rule
            articleRule() {

                return [
                    {
                        name: this.noteArticleForm.itemId,
                        validators: {
                            notEmpty: {
                                tip: "所属item不能为空"
                            },
                        }
                    },
                    {
                        name: this.noteArticleForm.sname,
                        validators: {
                            notEmpty: {
                                tip: "名字不能为空"
                            },
                            // regexp: {
                            //     reg: /^[a-zA-Z0-9_]+$/,
                            //     tip: '名字只能包含大写、小写、数字和下划线'
                            // }
                        }
                    },

                ];
            },

            fnLastPage() {

                if (this.page > this.pages) {

                    var n = this.pages;
                    this.fnPageChange(n);
                }
                if (this.page > 1) {

                    var n = this.page - 1;
                    this.fnPageChange(n);
                }
            },

            fnNextPage() {

                if (this.page > this.pages) {

                    var n = this.pages;
                    this.fnPageChange(n);
                }
                if (this.page < this.pages) {

                    var n = this.page + 1;
                    this.fnPageChange(n);
                }
            },


            fnPageChange(n) {

                this.page = n;
                this.queryItem();

            },

            //新增 article modal
            fnArticleModal() {

                var itemId = this.noteItemForm._id
                if (!itemId) {
                    alert('请选择 item');
                    return false;
                }

                this.noteArticleForm.itemId = itemId;
                $('#addArticleModal').modal('show');



            },

            //新增
            fnClear() {

                this.noteItemForm = {
                    cateId: '',
                };

                this.noteArticleList = [];
            },


            //修改 item
            fnUpdateItemModal(item) {

                // console.log(item);
                this.noteItemForm = item;
                this.noteItemForm["cateId"] = this.noteItemForm.cateId || '';
                // this.noteItemForm["cateId"] = '';
                // console.dir(this.noteItemForm);

                this.queryArticle(item._id);
            },


            //必填字段 验证工具
            validatorRule(ruleArr) {

                for (var i = 0; i < ruleArr.length; i++) {
                    var item = ruleArr[i];
                    var validators = item.validators;
                    for (var key in validators) {

                        if ("notEmpty" == key) {
                            if (!item.name) {
                                alert(validators[key].tip);
                                return false;
                            }
                        }

                        if ("regexp" == key) {
                            if (!validators[key].reg.test(item.name)) {
                                alert(validators[key].tip);
                                return false;
                            }
                        }

                    }
                }

                return true;
            },


            //新增，修改 item 保存
            fnAddOrUpdate() {

                if (!this.validatorRule(this.itemRule())) {
                    return;
                }

                var _self = this;

                var postUrl = '../notes/items/add';
                if (this.noteItemForm._id) {
                    postUrl = '../notes/items/update'
                }
                $.ajax({
                    // crossDomain: true,
                    type: "post",
                    url: postUrl,
                    data: _self.noteItemForm,
                    dataType: "json",
                    success: function (response) {
                        console.log(response);
                        if (response.code == 0) {

                            _self.noteItemForm = response.dat;
                            _self.queryItem();
                        }

                    }
                });
            },

            // 查询 cate
            queryCate() {

                var _self = this;
                $.ajax({
                    // crossDomain: true,
                    type: "get",
                    url: "../notes/cates",
                    // data: "data",
                    dataType: "json",
                    success: function (response) {
                        // console.log(response);
                        if (response.code == 0) {

                            _self.noteCateList = response.dat;
                            // console.log(response);
                        }

                    }
                });
            },

            queryItem() {

                var _self = this;
                $.ajax({
                    // crossDomain: true,
                    type: "get",
                    url: "../notes/items?page=" + _self.page,
                    // data: "data",
                    data: _self.noteItemSearchForm,
                    dataType: "json",
                    success: function (response) {
                        if (response.code == 0) {

                            _self.noteItemList = response.dat.records;
                            _self.total = response.dat.total;
                            // console.log(response);
                        }

                    }
                });

            },
            queryArticle(_itemId) {

                var _self = this;
                $.ajax({
                    // crossDomain: true,
                    type: "get",
                    url: "../notes/articles",
                    // data: "data",
                    data: {
                        itemId: _itemId
                    },
                    dataType: "json",
                    success: function (response) {
                        if (response.code == 0) {

                            _self.noteArticleList = response.dat;
                            // console.log(response);
                        }

                    }
                });

            },


            initSummernote() {

                $('#summernote1').summernote({

                    lang: 'zh-CN',
                    // placeholder: placeholder,
                    minHeight: 300,
                    dialogsFade: true, // Add fade effect on dialogs
                    dialogsInBody: true, // Dialogs can be placed in body, not in
                    // summernote.
                    // disableDragAndDrop: false,// default false You can disable drag
                    // and drop
                    callbacks: {
                        onImageUpload: function (files, editor, $editable) {

                            // FormData，新的form表单封装，具体可百度，但其实用法很简单，如下
                            var data = new FormData();

                            // 将文件加入到file中，后端可获得到参数名为“file”
                            data.append("uploadFile", files[0]);

                            // ajax上传
                            $.ajax({
                                data: data,
                                type: "POST",
                                url: "/files/summernote", // div上的action
                                cache: false,
                                contentType: false,
                                processData: false,

                                // 成功时调用方法，后端返回json数据
                                success: function (response) {

                                    console.log(response);

                                    if (response.code == 0) {

                                        // editor.insertImage($editable, '../' + response.path);
                                        $("#summernote1").summernote('insertImage',
                                            '../' + response.path);
                                    }
                                },
                                // ajax请求失败时处理
                                error: function () {
                                    alert("上传失败！")
                                }
                            });



                        }
                    }
                });

                $('#summernote1').summernote('fontSize', 20);

            },

            //article 保存 
            fnAddArticle() {

                if (!this.validatorRule(this.articleRule())) {
                    return;
                }
                var _self = this;

                var postUrl = '../notes/articles/add';
                // if (this.noteItemForm._id) {
                //     postUrl = '../notes/items/update'
                // }

                var markupStr = $('#summernote1').summernote('code');
                var postData = _self.noteArticleForm;
                postData.stext = markupStr;
                // var sHTML = $('.summernote').code();
                $.ajax({
                    // crossDomain: true,
                    type: "post",
                    url: postUrl,
                    data: postData,
                    dataType: "json",
                    success: function (response) {
                        // console.log(response);
                        if (response.code == 0) {

                            // _self.noteArticleForm = response.dat;
                            // _self.queryItem();

                            var itemId = _self.noteArticleForm.itemId;
                            _self.queryArticle(itemId);
                            _self.noteArticleForm = {
                                itemId: '',
                            };
                            $('#addArticleModal').modal('hide');
                            $("#summernote1").summernote('code', '');

                        }

                    }
                });

            },

            fnShowDetail(obj) {
                // this.noteArticleDetail = obj;
                window.open('articleDetail.html?_id=' + obj._id);
            }
        },
        mounted() {

            this.queryCate();
            this.queryItem();
            this.initSummernote();
        }
    })
</script>